package com.li.service;

import com.li.model.RegionStates;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;

@Service
public class CsvDataService implements InitializingBean {
    private WebClient webClient;
    private final ArrayList<RegionStates> allRegionStates=new ArrayList<>();
    public ArrayList<RegionStates> getAllRegionStates() {
        return allRegionStates;
    }
    @Scheduled(cron = "0 0 1 * * *")
    public void fetchCoronaVirusData() throws IOException {
        webClient = WebClient.builder()
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(3 * 1024 * 1024))
                .baseUrl("https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv")
                .defaultHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)")//设置UA
                .build();

        Mono<Resource> mono = webClient.get().retrieve().bodyToMono(Resource.class);//
        Resource body = mono.block();
        //获取csv文件的输入流
        InputStream inputStream = body.getInputStream();
        final Reader reader = new InputStreamReader(inputStream);
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(reader);
        for (final CSVRecord record : records) {
            RegionStates regionStates = new RegionStates();
            int today = Integer.parseInt(record.get(record.size() - 1));
            int yesterday = Integer.parseInt(record.get(record.size() - 2));
            if ((record.get("Province/State")).equals("") || (record.get("Province/State")) == null)
                regionStates.setState(record.get("Country/Region"));
            else
                regionStates.setState(record.get("Province/State"));
            regionStates.setCountry(record.get("Country/Region"));
            regionStates.setLatestTotalCases(today);
            regionStates.setDiffFromPrevDay(today - yesterday);
            allRegionStates.add(regionStates);
        }
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        fetchCoronaVirusData();
    }


}



